package com.xinhe.cn.cpbox.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinhe.cn.cpbox.common.Result;
import com.xinhe.cn.cpbox.entity.po.MatchMaker;
import com.xinhe.cn.cpbox.entity.po.ScripSend;
import com.xinhe.cn.cpbox.entity.po.SysUser;
import com.xinhe.cn.cpbox.entity.po.UserRecord;
import com.xinhe.cn.cpbox.mapper.*;
import com.xinhe.cn.cpbox.security.JwtUtil;
import com.xinhe.cn.cpbox.service.ManagementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author HB
 * @date 2021/03/22 15:23
 */
@Service
@Slf4j
public class ManagementServiceImpl implements ManagementService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SystemConstantMapper systemConstantMapper;
    @Autowired
    MatchMakerMapper matchMakerMapper;
    @Autowired
    UserRecordMapper userRecordMapper;
    @Autowired
    ScripSendMapper scripSendMapper;

    @Override
    public Object test() {
        return Result.ok();
    }

    @Override
    public Object login(JSONObject jsonObject) {
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return Result.paramError();
        }

        // 根据用户查询到用户
        SysUser sysUser = sysUserMapper.selectByUsername(username);
        if (Objects.isNull(sysUser)) {
            return Result.error().message("找不到此用户");
        }
        if (sysUser.getError() > 5) {
            return Result.error().message("登录失败次数超过5次");
        }

        // 加密密码
        String s = SecureUtil.sha1(password);
        if (sysUser.getPassword().equals(s)) {
            String token = JwtUtil.sign(username, s);  // 生成token返回给前端
            sysUser.setError(0);    // 错误次数清零
            sysUserMapper.updateById(sysUser);
            return Result.ok().data("token", token);
        } else {
            sysUser.setError(sysUser.getError() + 1);
            sysUserMapper.updateById(sysUser);
        }
        return Result.error();
    }

    @Override
    public Object getCashOutApply(int type, int page, int size) {
        if (type < -1 || type > 1 || page < 0 || size <= 0) {
            return Result.paramError();
        }

        // 查询条件
        QueryWrapper<MatchMaker> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(type != -1, "has_apply", type).isNotNull("apply_time")
                .orderByAsc(type == 1, "apply_time")    // 查询未处理提现申请时，排序按时间升序
                .orderByDesc(type != 1, "apply_time");  // 查询已处理提现申请/全部申请时，排序按时间降序
        // 分页
        Page<MatchMaker> mpPage = new Page<>(page, size);
        // 查询
        IPage<MatchMaker> iPage = matchMakerMapper.selectPage(mpPage, queryWrapper);
        // 返回总页数和数据
        return Result.ok().data("totalPage", iPage.getPages()).data("matchMakers", iPage.getRecords());
    }

    @Override
    public Object completeMoneyApply(JSONObject jsonObject) {
        String matchMakerId = jsonObject.getString("matchMakerId");
        String money = jsonObject.getString("money");

        if (StringUtils.isBlank(matchMakerId) || StringUtils.isBlank(money)) {
            return Result.paramError();
        }

        // 扣除余额
        matchMakerMapper.completeMoneyApply(money, matchMakerId);
        // 生成用户记录
        UserRecord userRecord = new UserRecord();
        userRecord.setContent("提现-" + money);
        userRecord.setOpenId(matchMakerId);
        userRecord.setCreateTime(DateUtil.now());
        userRecordMapper.insert(userRecord);

        return Result.ok();
    }

    @Override
    public Object getScrip(int type, int page, int size) {
        if (type < -1 || type > 2 || page < 0 || size <= 0) {
            return Result.paramError();
        }

        // 查询条件
        QueryWrapper<ScripSend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(type != -1, "checked", type).orderByDesc("send_time");
        // 分页
        Page<ScripSend> mpPage = new Page<>(page, size);
        // 查询
        IPage<ScripSend> iPage = scripSendMapper.selectPage(mpPage, queryWrapper);
        // 返回总页数和数据
        return Result.ok().data("totalPage", iPage.getPages()).data("scrips", iPage.getRecords());
    }

    @Override
    public Object checkScrip(JSONObject jsonObject) {
        String checked = jsonObject.getString("checked");
        String scripId = jsonObject.getString("scripId");
        String rejectReason = jsonObject.getString("rejectReason");

        if (StringUtils.isBlank(checked) || StringUtils.isBlank(scripId) || (!"1".equals(checked) && !"2".equals(checked))) {
            return Result.paramError();
        }

        if("1".equals(checked)) {
            rejectReason = null;
        }

        UpdateWrapper<ScripSend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("scrip_id", scripId).set("checked", checked).set("reject_reason", rejectReason);
        scripSendMapper.update(null, updateWrapper);

        return Result.ok();
    }
}
